package com.geekstudy.week12;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class ActiveMQJMSTopicDemo {

    public static void main(String[] args) {

        try {
            String jmsUrl = "tcp://127.0.0.1:61616";
            String topicName = "demo.java4.topic";

            TopicConnectionFactory topicConnectionFactory = new ActiveMQConnectionFactory(
                    ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, jmsUrl
            );
            TopicConnection connection = topicConnectionFactory.createTopicConnection();
            connection.start();

            TopicSession session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic(topicName);

            // 订阅消息
            TopicSubscriber topicSubscriber = session.createSubscriber(topic);
            topicSubscriber.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    if(message == null) {
                        System.out.println(" message is null ");
                    }
                    if(message instanceof TextMessage) {
                        TextMessage onMessage = (TextMessage)message;
                        try {
                            System.out.println(" 订阅消息:" + onMessage.getText());
                        } catch(Exception e) {
                            System.out.println(" message getText exception");
                            e.printStackTrace();
                        }
                    }
                }
            });
            session.commit();
            System.out.println(" subscriber success !");

            // 发送 Topic 消息
            TopicPublisher topicPublisher = session.createPublisher(topic);
            topicPublisher.setDeliveryMode(DeliveryMode.PERSISTENT);
            String message = "发送测试消息 demo 202109";
            TextMessage textMessage = session.createTextMessage(message);
            topicPublisher.send(textMessage);
            session.commit();
            System.out.println(" send message success");


            // 订阅消息后退出
            Thread.sleep(1000 * 10);


            session.close();
            connection.close();

        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
